package cn.tonyandmoney.voicenotes.ui.activity

import android.os.Bundle
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import android.widget.LinearLayout
import cn.tonyandmoney.voicenotes.R
import cn.tonyandmoney.voicenotes.notes.bean.ReaderState
import cn.tonyandmoney.voicenotes.notes.enums.OperationEnum
import cn.tonyandmoney.voicenotes.notes.presenter.IReaderInterface
import cn.tonyandmoney.voicenotes.notes.presenter.ReaderPresenter
import cn.tonyandmoney.voicenotes.ui.component.ReaderStateComponent
import cn.tonyandmoney.voicenotes.utils.DateUtils
import com.afollestad.materialdialogs.MaterialDialog
import com.zlzsy.app.base.ui.BaseActivity
import org.jetbrains.anko.*
import java.util.*

/**
 * 语音笔记录入功能
 * 界面
 * --------
 * 开始录音
 * ----------
 * 笔记名称| 开始录音按钮
 * ---------------
 * 笔记内容
 * --------------
 * 文件名称
 * ----
 * 语音识别内容
 * 实现全语音录入
 * 所以及页面自动开启语音控制
 * 但是只有在录入内容的时候才会保存语音笔记
 */
class NoteReaderActivity : BaseActivity(), IReaderInterface, ReaderStateComponent.IDialogListener {

    private val mPresenter: ReaderPresenter by lazy { ReaderPresenter(this, this) }
    private val mStateDialog: ReaderStateComponent by lazy { ReaderStateComponent(this) }
    private lateinit var mContentView: EditText
    private lateinit var mNameView: EditText
    private lateinit var mMemoView: EditText
    private lateinit var mTypeView: EditText

    private val mDateTime:String by lazy { DateUtils.formatter(Date(), DateUtils.YYYYMMDDHHmmss) }


    override fun initView() {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        frameLayout {
            verticalLayout {
                linearLayout {
                    orientation = LinearLayout.HORIZONTAL
                    backgroundResource = android.R.color.white
                    padding = dip(10)
                    textView {
                        text = "笔记名称："
                    }.lparams(wrapContent, wrapContent)
                    editText {
                        id = R.id.record_name
                        mNameView = this
                        backgroundResource = android.R.color.transparent
                        hint = "请输入..."
                        singleLine = true
                        gravity = Gravity.TOP or Gravity.START
                        setText(mDateTime)
                    }.lparams(0, wrapContent, 1f)

                    textView {
                        backgroundResource = R.drawable.bg_btn_ripper
                        gravity = Gravity.CENTER
                        text = "录入"
                        textColor = resources.getColor(android.R.color.white)
                        setOnClickListener {
                            mPresenter.operation(OperationEnum.INPUT_NAME)
                        }
                    }.lparams(dip(50), dip(30))
                    gravity = Gravity.CENTER_VERTICAL
                }.lparams(matchParent, wrapContent) {
                    topMargin = dip(10)
                }
                linearLayout {
                    orientation = LinearLayout.HORIZONTAL
                    backgroundResource = android.R.color.white
                    padding = dip(10)
                    textView {
                        text = "笔记分类："
                    }.lparams(wrapContent, wrapContent)
                    editText {
                        id = R.id.record_type
                        mTypeView = this
                        backgroundResource = android.R.color.transparent
                        hint = "请输入..."
                        singleLine = true
                        gravity = Gravity.TOP or Gravity.START
                    }.lparams(0, wrapContent, 1f)
                    textView {
                        backgroundResource = R.drawable.bg_btn_ripper
                        gravity = Gravity.CENTER
                        text = "录入"
                        textColor = resources.getColor(android.R.color.white)
                        setOnClickListener {
                            mPresenter.operation(OperationEnum.INPUT_TYPE)
                        }
                    }.lparams(dip(50), dip(30))
                    gravity = Gravity.CENTER_VERTICAL
                }.lparams(matchParent, wrapContent) {
                    topMargin = dip(10)
                }
                linearLayout {
                    orientation = LinearLayout.HORIZONTAL
                    backgroundResource = android.R.color.white
                    padding = dip(10)
                    textView {
                        text = "笔记备注："
                    }.lparams(wrapContent, wrapContent)
                    editText {
                        id = R.id.record_memo
                        mMemoView = this
                        backgroundResource = android.R.color.transparent
                        hint = "请输入..."
                        singleLine = true
                        gravity = Gravity.TOP or Gravity.START
                    }.lparams(0, wrapContent, 1f)
                    textView {
                        backgroundResource = R.drawable.bg_btn_ripper
                        gravity = Gravity.CENTER
                        text = "录入"
                        textColor = resources.getColor(android.R.color.white)
                        setOnClickListener {
                            mPresenter.operation(OperationEnum.INPUT_MEMO)
                        }
                    }.lparams(dip(50), dip(30))
                    gravity = Gravity.CENTER_VERTICAL
                }.lparams(matchParent, wrapContent) {
                    topMargin = dip(10)
                }
                verticalLayout {
                    backgroundResource = android.R.color.white
                    padding = dip(10)
                    frameLayout {
                        textView {
                            text = "笔记内容："
                            topPadding = dip(15)
                        }.lparams(wrapContent, wrapContent)
                        textView {
                            backgroundResource = R.drawable.bg_btn_ripper
                            gravity = Gravity.CENTER
                            text = "录入"
                            textColor = resources.getColor(android.R.color.white)
                            setOnClickListener {
                                mPresenter.operation(OperationEnum.INPUT_CONTENT)
                            }
                        }.lparams(dip(50), dip(30)) {
                            gravity = Gravity.END
                        }
                    }.lparams(matchParent, wrapContent)

                    scrollView {
                        editText {
                            mContentView = this
                            id = R.id.record_content
                            backgroundResource = android.R.color.transparent
                            hint = "请输入..."
                            gravity = Gravity.TOP or Gravity.START
                        }.lparams(matchParent, matchParent)
                    }.lparams(matchParent, matchParent)
                }.lparams(matchParent, 0, 1f)

                textView {
                    backgroundResource = R.drawable.btn_round_corner
                    text = "确定"
                    setTextColor(resources.getColor(android.R.color.white))
                    setOnClickListener { mPresenter.saveNote() }
                    gravity = Gravity.CENTER
                    textSize = 18f
                    leftPadding = dip(15)
                    rightPadding = dip(15)
                }.lparams(matchParent, dip(45)) {
                    topMargin = dip(15)
                }

            }.lparams(matchParent, matchParent)
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        showLoadingDialog(R.string.is_data_init)
        mPresenter.init(this)
    }

    /**
     * 不管是保存成功还是失败，为了简便，都做退出处理，
     * @param code  0表示成功，-1表示失败
     */
    override fun saveResult(code: Int, msg: String) {
        longToast(msg)
        finish()
    }

    override fun hideState() {
        mStateDialog.hide()
    }

    override fun onEnable(enable: Boolean) {
        if (enable) {
            hideLoadingDialog()
        }
    }

    override fun getInputText(id: Int): String {
        return find<EditText>(id).text.toString()
    }

    /**
     * 当监听到用户发音：笔记名称：之后的回调
     */
    override fun onName(name: String) {
        mStateDialog.update(name)
        if (mNameView.text.toString()==mDateTime){
            mNameView.post { mNameView.setText(name) }
        }else{
            mNameView.post { mNameView.append(name) }
        }
    }


    /**
     * 当监听到用户发音 备忘录：回调
     */
    override fun onMemo(memo: String) {
        mStateDialog.update(memo)
        mMemoView.post { mMemoView.append(memo) }
    }

    override fun onType(type: String) {
        mStateDialog.update(type)
        mTypeView.post { mTypeView.append(type) }
    }

    /**
     * 当监听到用户发音：笔记内容： 回调
     * @param content  当前识别的内容
     */
    override fun onPartialContent(content: String) {
        mStateDialog.update(content)
        mContentView.post { mContentView.append(content) }
    }

    /**
     * 取消当前输入
     * 这个要不要实现，看情况吧
     */
    override fun onCancel(state: ReaderState) {
        mPresenter.operation(OperationEnum.CANCEL)
    }

    /**
     * 结束当前的输入
     */
    override fun onConfirm(state: ReaderState) {
        mPresenter.operation(OperationEnum.CONFIRM)
    }

    /**
     * 不清楚内容，保留上一次内容
     */
    override fun onState(state: ReaderState) {
        runOnUiThread {
            when (state.operation) {
                OperationEnum.INPUT_NAME -> mNameView.requestFocus()
                OperationEnum.INPUT_TYPE -> mTypeView.requestFocus()
                OperationEnum.INPUT_MEMO -> mMemoView.requestFocus()
                OperationEnum.INPUT_CONTENT -> mContentView.requestFocus()
                else -> {
                }
            }
            mStateDialog.show()
            mStateDialog.update(state)
        }
    }


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.note_reader, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.action_help) {
            MaterialDialog.Builder(this)
                    .title("帮助")
                    .content(R.string.note_reader_helper)
                    .positiveText(R.string.confirm)
                    .show()
            return true
        } else if (item.itemId == R.id.action_cmd) {
            MaterialDialog.Builder(this)
                    .title("指令说明")
                    .content(R.string.note_reader_cmd)
                    .positiveText(R.string.confirm)
                    .show()
            return true
        }
        return super.onOptionsItemSelected(item)
    }


    override fun onDestroy() {
        mPresenter.onExit()
        super.onDestroy()
    }

}